package com.the_ring.chapter11.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

public class ClickView extends View {

    private Paint mPaint = new Paint();     // 声明一个画笔对象
    private long mLastTime;                 // 上次按下手指的系统时间
    private PointF mPos;                    // 按下手指的坐标点
    private float mPressure = 0;                // 按压的压力值
    private int dip_10;

    public ClickView(Context context) {
        this(context, null);
    }

    public ClickView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        dip_10 = dip2px(context, 10);
        mPaint.setColor(Color.DKGRAY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        if (mPos != null) {
            // 以按压点为圆心、压力值为半径在画布上绘制圆心
            canvas.drawCircle(mPos.x, mPos.y, dip_10 * mPressure, mPaint);
        }
    }

    // 在发生触摸事件时触发
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN || (event.getPressure() > mPressure)) {
            mPos = new PointF(event.getX(), event.getY());
            mPressure = event.getPressure();
        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mLastTime = event.getEventTime();
                break;
            case MotionEvent.ACTION_UP:
                if (mListener != null) {
                    mListener.onLift(event.getEventTime() - mLastTime, mPressure);
                }
                break;
        }
        postInvalidate();
        return true;
    }

    // 根据是手机的分辨率从 dp 的单位转化为 px
    public int dip2px(Context context, float dpValue) {
        // 获取手机像素密度（1dp 对应几个 px）
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f); // 四舍五入取整
    }

    private LiftListener mListener;

    public void setLiftListener(LiftListener mListener) {
        this.mListener = mListener;
    }

    public interface LiftListener {
        void onLift(long time_interval, float pressure);
        /**
         * time_interval > 500 ? "长按" : "点击";
         */
    }
}
